import React, {Component} from 'react';
import {
  View,
  Text,
  TouchableOpacity,
  Image,
  ListView,
  Keyboard,
  Platform,
  Animated,
  TextInput,
  Alert,
} from 'react-native';

import Config from '../../config';
import SizeUtils from '../../common/SizeUtils';
import ToastUtils from '../../common/ToastUtils';
import {DateUtils} from '../../utils/Utils';
import CommonChatItemView from '../common/CommonChatItemView';
import BasePage from '../common/BasePage';
import LoginCheckIsUserAction from '../../actions/login/LoginCheckIsUserAction';

const MAX_PAGE = 5;

export const RefreshTitle={
  pullToRefresh:'上拉刷新',
  releaseToRefresh:'松开以刷新',
  refreshing:'正在刷新数据'
}

export const RefreshStatus={
  no:-1,
  pullToRefresh:0,
  releaseToRefresh:1,
  refreshing:2,
}

export const LoadMoreTitle={
  pullToLoadMore:'下拉加载更多记录',
  releaseToLoadMore:'松开以加载更多记录',
  loadMoring:'正在加载更多记录'
}

export const LoadMoreStatus={
  no:-1,
  pullToLoadMore:0,
  releaseToLoadMore:1,
  loadMoring:2,
}
const REFRESH_HEADER_HEIGHT = 140;

export default class CommonChatPage extends BasePage {
  constructor(props) {
    super(props);

    this._keyboardWillShowListener = null;
    this._keyboardDidShowListener = null;
    this._keyboardWillHideListener = null;
    this._keyboardDidChangeListener = null;

    this._ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    this._firstEnd = true;
    this._currentPage = 1;
    this._initTimer = null;
    this._initComplete = false;
    this._listView = null;
    this._offsetY = 0;
    this._dragFlag = false; //是否处于拖动状态的标志
    this._refreshing = false;
    this._refreshInterval = null;//定时刷新数据
    this._refreshOutTimer = null;//用来请求超时后修改状态
    this._refreshIntervalTimer = null; //用来控制请求的频率
    this._needToEnd = false;
    this._autoMove = false;
    this._viewHeight = SizeUtils.getWindowSize().height - SizeUtils.translateDesignHeightToCode(100 + 20);
    this._viewWidth = SizeUtils.getWindowSize().width;
    this._contentHeight = this._viewHeight;
    this._isAtEnd = true;//是否在底部
    this._isAtTop = true;//是否在顶部
    this._dataSave = [];
    this._isKeyboardShow = false;
    this._scrollTimer = null;//根据键盘滚动视图

    this.state.keyboardHeight = 0;
    this.state.dataSource = this._ds.cloneWithRows([]);
    this.state.refreshTitle = "";
    this.state.refresStatus = -1;
    this.state.loadMoreTitle = "";
    this.state.loadMoreStatus = -1;
    this.state.showLoadMore = false;

    this._startRefreshInterval();
  }

  _startRefreshInterval() {
    this._clearRefreshInterval();
    this._refreshInterval = setInterval(()=>{
      if(this._dragFlag === true) {
        return;
      }
      this._refresh();
    }, 5 * 1000);
  }

  _clearRefreshInterval() {
    this._refreshInterval && clearInterval(this._refreshInterval);
  }

  _dealEnterPage() {
    this._startRefreshInterval();
    this._refresh();
  }

  _dealLeavePage() {
    this._clearRefreshInterval();
    this.clear();
  }

  _getUserData() {

  }

  clear() {
    let dataSource = this._ds.cloneWithRows([]);
    this._dataSave = [];
    this.setState({
      dataSource:dataSource,
    })
  }

  componentDidMount() {
    this._initTimer = setTimeout(()=>{
     clearTimeout(this._initTimer)
     this._refresh();
    }, 500);

    this._keyboardWillShowListener = Keyboard.addListener('keyboardWillShow', this._keyboardWillShow.bind(this));
    this._keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow.bind(this));

    if(Platform.OS === "ios") {
      this._keyboardWillHideListener = Keyboard.addListener('keyboardWillHide', this._keyboardWillHide.bind(this));
    }
    else{
      this._keyboardWillHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide.bind(this));
    }
    this._keyboardDidChangeListener = Keyboard.addListener('keyboardDidChangeFrame', this._keyboardDidChange.bind(this));
  }

  componentWillUpdate(nextProps, nextState) {
    super.componentWillUpdate(nextProps, nextState);
    if(nextState.keyboardHeight != this.state.keyboardHeight) {
      this._viewHeight = SizeUtils.getWindowSize().height - SizeUtils.translateDesignHeightToCode(100 + 20) - nextState.keyboardHeight;
    }
    if(nextState.isResponeUpdate === true) {
      nextState.isResponeUpdate = false;
      this._onFinish(1, nextState.data);
    }
  }

  componentWillUnmount() {
    this._keyboardWillShowListener.remove();
    this._keyboardDidShowListener.remove();
    this._keyboardWillHideListener.remove();
    this._keyboardDidChangeListener.remove();

    this._clearRefreshOutTimer();
    this._clearRefreshIntervalTimer();
  }

  /**
   * 滑动中
   * @param event
   * @private
   */
  _onScroll(event){
    let y = event.nativeEvent.contentOffset.y
    this._offsetY = y
    // console.log("_onScroll", y, this.props.style.height);
    if (this._dragFlag){
      let height = SizeUtils.translateDesignHeightToCode(REFRESH_HEADER_HEIGHT);
      if (!this._isRefreshing){
        if (y <= -height){
          this.setState({
            loadMoreStatus:LoadMoreStatus.releaseToLoadMore,
            loadMoreTitle:LoadMoreTitle.releaseToLoadMore,
          })
        }
        else if (y <= -height/2){
          this.setState({
            loadMoreStatus:LoadMoreStatus.pullToLoadMore,
            loadMoreTitle:LoadMoreTitle.pullToLoadMore,
          })
        }
        else if(this._viewHeight + this._offsetY > this._contentHeight) {
          if(this._viewHeight + this._offsetY > this._contentHeight + 100) {
            this.setState({
              refresStatus:RefreshStatus.releaseToRefresh,
              refreshTitle:RefreshTitle.releaseToRefresh,
            });
          }
          else {
            this.setState({
              refresStatus:RefreshStatus.pullToRefresh,
              refreshTitle:RefreshTitle.pullToRefresh,
            });
          }
        }
        else {
          //下拉以刷新
          this.setState({
            refresStatus:RefreshStatus.no,
            refreshTitle:RefreshTitle.no,
            loadMoreStatus:LoadMoreStatus.no,
            loadMoreTitle:LoadMoreTitle.no,
          })
        }
      }
    }
    if(this._contentHeight <= this._viewHeight + this._offsetY + 20) {//20为容错处理
      this._isAtEnd = true;
      console.log("到底了");
    }
    else
    {
      this._isAtEnd = false;
    }
    this._isAtTop = false;
    if(this._offsetY <= 0) {
      this._isAtTop = true;
      console.log("到顶了");
    }

    this._dealError();
  }

  _dealError() {
    if(this._dragFlag === true && this._offsetY < -SizeUtils.getWindowSize().height/3) {
      this._scrollToTop();
    }
    else if(this._dragFlag === true && this._contentHeight > this._viewHeight && this._offsetY > this._contentHeight - this._viewHeight + SizeUtils.getWindowSize().height/3){
      this._scrollToEnd();
    }
  }

  _onScrollBeginDrag(event){
    this._dragFlag = true;
    this._autoMove = false;
    this._offsetY = event.nativeEvent.contentOffset.y;
  }

  _onContentSizeChange(contentWidth, contentHeight) {
    this._contentHeight = contentHeight + Config.paddingTop + SizeUtils.translateDesignHeightToCode(20);
    if(this._isAtEnd === true && this._offsetY < this._contentHeight - this._viewHeight) {
      this._scrollToEnd();
    }
  }

  _scrollTo(params) {
    if(this._listView === null || this._listView === undefined) {

    }
    else {
      this._listView.scrollTo(params);
    }
  }

  _scrollToTop() {
    if(this._listView === null || this._listView === undefined) {

    }
    else {
      this._listView.scrollTo({y:0});
    }
  }

  _scrollToEnd() {
    if(this._listView === null || this._listView === undefined) {

    }
    else if(this._contentHeight - this._viewHeight > 0) {
      this._listView.scrollTo(this._contentHeight - this._viewHeight);
    }
    else
    {
      this._listView.scrollTo({y:0});
    }
  }

  /**
   * 拖拽
   * @private
   */
  _onScrollEndDrag(event) {
    console.log("_onScrollEndDrag", this._offsetY, this._viewHeight, this._contentHeight, this._contentHeight - this._viewHeight);
    this._dragFlag = false;
    let y = event.nativeEvent.contentOffset.y
    this._offsetY = y
    let height = SizeUtils.translateDesignHeightToCode(REFRESH_HEADER_HEIGHT);
    if (!this._isRefreshing){
      if (this.state.loadMoreStatus == LoadMoreStatus.releaseToLoadMore){
        let result = this._loadMore();
        if(!result) return;
        if (y <= 0) {
          this._scrollTo({x:0,y:-height,animated:true});
        }
      }
      // else if (this.state.refresStatus == RefreshStatus.releaseToRefresh){
      //   let result = this._refresh();
      //   if(!result) return;
      //   if(this._contentHeight > this._viewHeight) {
      //     this._scrollTo({x:0,y:this._contentHeight - this._viewHeight + height,animated:true});
      //   }
      // }
    }
  }

  _onEndReached(event) {

  }

  _refresh() {
    if(!this._refreshing) {
      if(this._refreshIntervalTimer) {
        // ToastUtils.show("刷新太频繁");
        return false;
      }
      this._refreshing = true;
      this._refreshIntervalTimer = setTimeout(() => {
        this._clearRefreshIntervalTimer();
      }, this.props.refreshInterval ? this.props.refreshInterval : 1000);

      this.setState({
        refresStatus:RefreshStatus.refreshing,
        refreshTitle:RefreshTitle.refreshing,
      })
      this._doSendRefresh(1);
      return true;
    }
    return false;
  }

  _loadMore(params) {
    if(!this._refreshing) {
      if((!params || !params.force) && this._refreshIntervalTimer) {
        return false;
      }
      if(this._currentPage >= MAX_PAGE) {
        ToastUtils.show("无法查看更早的记录");
        return false;
      }
      this._refreshIntervalTimer = setTimeout(() => {
        this._clearRefreshIntervalTimer();
      }, this.props.refreshInterval ? this.props.refreshInterval : 1000);
      this._refreshing = true;
      this.setState({
        loadMoreStatus:LoadMoreStatus.loadMoring,
        loadMoreTitle:LoadMoreTitle.loadMoring
      })
      this._doSendRefresh(this._currentPage + 1);
      return true;
    }
    return false;
  }

  _doSendRefresh(page) {
    this._requestData(page);
    this._refreshOutTimer = setTimeout(() => {
      this._clearRefreshOutTimer();
      this._onFinish(2);
    }, 8000);
  }

  _onFinish(type, data, params) {
    if(this._refreshing) {
      let dataSource = null;
      if(type = 1 && data != null) {
        if(this.state.loadMoreStatus == LoadMoreStatus.loadMoring) {
          this._currentPage = this._currentPage + 1;
        }
      }
      this._dealData(type, data);
      this._onRefreshEnd(type == 2 || data == null ||data.length == 0);
    }
  }

  _dealData(type, data) {
    let copyDataSave = [];
    if(type != 2 && data != null) {
      copyDataSave = this._dataSave.length === 0 ? [] : this._dataSave.concat();
      for (var i = 0; i < data.length; i++) {
        let exist = false;
        for (var j = 0; j < this._dataSave.length; j++) {
          if(this._dataSave[j].msg_id === data[i].msg_id) {
              copyDataSave[j] = data[i];
              exist = true;
              break;
          }
        }
        if(!exist) {
          copyDataSave.push(data[i]);
        }
      }
    }
    this._dataSave = copyDataSave.sort(this._sortData.bind(this));
    dataSource = this._ds.cloneWithRows(this._dataSave);

    this.setState({
      dataSource:dataSource,
    })
  }

  _sortData(aData, bData) {
    let aDate1 = DateUtils.getDate(aData.sent_at);
    let bDate2 = DateUtils.getDate(bData.sent_at);
    return DateUtils.compareDate(aDate1, bDate2);
  }

  /**
   * 刷新结束
   * @private
   */
  _onRefreshEnd(noData){
    console.log("_onRefreshEnd");
    this._clearRefreshOutTimer();
    this._refreshing = false;
    if(this.state.refresStatus === RefreshStatus.refreshing && this._isAtEnd && this._contentHeight > this._viewHeight) {
      // this._scrollToEnd();
    }
    else if(this.state.loadMoreStatus === LoadMoreStatus.loadMoring) {
      this._scrollToTop();
    }

    this.setState({
      refresStatus:RefreshStatus.no,
      loadMoreStatus:LoadMoreStatus.no,
    })
  }

  _clearRefreshOutTimer() {
    this._refreshOutTimer && clearTimeout(this._refreshOutTimer);
    this._refreshOutTimer = null;
  }

  _clearRefreshIntervalTimer() {
    this._refreshIntervalTimer && clearTimeout(this._refreshIntervalTimer);
    this._refreshIntervalTimer = null;
  }

  _dealRender() {
    return(
      <View style={{flexDirection:"column", width:this._viewWidth,
            height:SizeUtils.getWindowSize().height}}>
        <View style={{height:this._viewHeight,
            paddingTop:Config.paddingTop + SizeUtils.translateDesignHeightToCode(20)}}>
          {/* {this._renderRefresh()} */}
          {this._renderLoadMore()}
          <ListView
            ref={(ref)=>{this._listView = ref}}
            style={{height:this._viewHeight,}}
            enableEmptySections={true}
            scrollEventThrottle={60}
            onScroll={this._onScroll.bind(this)}
            onScrollBeginDrag={(event)=>this._onScrollBeginDrag(event)}
            onScrollEndDrag={(event)=>this._onScrollEndDrag(event)}
            onEndReachedThreshold={1}
            overScrollMode={"always"}
            onEndReached={(event)=>this._onEndReached(event)}
            dataSource={this._getDataSource()}
            onContentSizeChange = {this._onContentSizeChange.bind(this)}
            // renderHeader={this._onRenderHeader.bind(this)}
            renderRow={this._onRenderItem.bind(this)}
            showsHorizontalScrollIndicator={false}  // 隐藏水平指示器
            showsVerticalScrollIndicator={false}    // 隐藏垂直指示器
            automaticallyAdjustContentInsets = {false}
          >
          </ListView>
        </View>
        {this._renderCommentFooter()}
        {this._renderNavigationBar()}
      </View>
    )
  }

  _getDataSource() {
    return this.state.dataSource;
  }

  _renderLoadMore() {
    if(this._isAtTop === false) {
      return;
    }
    return (
      <View style={{width:this._viewWidth,
          height:SizeUtils.translateDesignHeightToCode(REFRESH_HEADER_HEIGHT),
          position:"absolute", top:Config.paddingTop, justifyContent:"center",
          alignItems:"center", backgroundColor:"#00000000", borderWidth:0}}>
        <Text style={{color:"#373737",
          backgroundColor:"#00000000", borderWidth:0}}>
          {this.state.loadMoreStatus > -1 ? this.state.loadMoreTitle : ""}
        </Text>
      </View>
    )
  }

  _renderRefresh() {
    return(
      <View style={{position:"absolute", width:this._viewWidth,
          bottom:SizeUtils.translateDesignHeightToCode(20)}}>
        <Text style={{textAlign:"center"}}>
          {this.state.refresStatus > -1 ? this.state.refreshTitle : ""}
        </Text>
      </View>
    )
  }

  _onRenderItem(data, index) {
    return <CommonChatItemView data={data} userData={this._getUserData()}/>
  }

  _renderCommentFooter() {
    return(
      <Animated.View style={{position:"absolute",
        bottom:this.state.keyboardHeight,
        flexDirection:"row",
        alignItems:"center",
        justifyContent:"space-between",
        backgroundColor:"#ffffff",
        paddingTop: SizeUtils.translateDesignHeightToCode(10),
        paddingLeft: SizeUtils.translateDesignHeightToCode(40),
        paddingRight: SizeUtils.translateDesignHeightToCode(40),
        paddingBottom: SizeUtils.translateDesignHeightToCode(10),
        width:SizeUtils.getWindowSize().width,
        height: Math.max(SizeUtils.translateDesignHeightToCode(104), this.state.inputContentheight + SizeUtils.translateDesignHeightToCode(8)),
        shadowColor: '#000000',
        shadowOffset: {
          width: 0,
          height: SizeUtils.translateDesignNumToCode(5),
        },
        shadowRadius: SizeUtils.translateDesignNumToCode(10),
        shadowOpacity: 0.1,
        }}>
        <TextInput
          style={{padding:0,flex:1,
            fontSize:SizeUtils.translateFontSizeToCode(30),
            paddingLeft:SizeUtils.translateDesignWidthToCode(40),
            paddingRight:SizeUtils.translateDesignWidthToCode(40),
            lineHeight:SizeUtils.translateDesignHeightToCode(60),
            borderWidth:SizeUtils.translateDesignNumToCode(4),
            borderRadius: SizeUtils.translateDesignNumToCode(10),
            borderColor:"#eeeeee",
            // height: Math.max(SizeUtils.translateDesignHeightToCode(96), this.state.),
            }}
          onChangeText = {(comment) => this.setState({comment})}
          placeholder = "输入内容"
          multiline = {false}
          onSubmitEditing = {() => this._sendComment()}
          value = {this.state.comment}
          underlineColorAndroid="transparent"
          multiline = {true}
          onContentSizeChange={this._onInputContentSizeChange.bind(this)}
        />
        <TouchableOpacity onPress = {() => this._sendComment()}
          disabled = {this.state.viewStatus == 2}
          style = {{ backgroundColor:"#D93338",
          flexDirection: 'row',
          alignItems: 'center',
          justifyContent: 'center',
          marginLeft:SizeUtils.translateDesignWidthToCode(40),
          height: Math.max(SizeUtils.translateDesignHeightToCode(70), 0 ),
          width: SizeUtils.translateDesignWidthToCode(130),
          borderRadius: SizeUtils.translateDesignNumToCode(10),
          }}
          >
          <Text style={{ borderWidth:0,
            color: '#ffffff',
            fontSize:SizeUtils.translateFontSizeToCode(30)}}>
            发送
          </Text>
        </TouchableOpacity>
      </Animated.View>
    )
  }

  _onInputContentSizeChange(event) {
    this.setState({inputContentheight: event.nativeEvent.contentSize.height + 15 });
  }

  _sendComment() {
    if(this.state.comment == "") {
      Alert.alert('提示','内容不能为空',[
          {text:'确定',onPress:()=>{}}
        ])
      return;
    }
    new LoginCheckIsUserAction().call(this, {content:"你是游客身份，不能聊天"}, this._onCheckIsUserCallback.bind(this))
  }

  _onCheckIsUserCallback(result) {
    if(result) {

    }
  }

  _requestData(page) {
    this._refreshOutTimer = setTimeout(() => {
      this._clearRefreshOutTimer();
      let testData = [];
      for (var i = 10 * (page - 1); i < 10 * page; i++) {
        testData.push({msg_id:i, nick:"nick" + i, content:"content" + i, isSelf:i%2 === 0});
      }
      this._onFinish(1, testData);
    }, 2000);
  }

  _delayScrollView(keyboardHeight) {
    this._clearDelayScrollTimer();
    let self = this;
    this._scrollTimer = setTimeout(()=>{
     clearTimeout(self._scrollTimer);
     if(self._isAtEnd == true) {
        self._scrollToEnd();
     }
     else {
       let y = 0;
       if(self.state.keyboardHeight > 0) {
         y = self._offsetY + self.state.keyboardHeight;
         if(y > self._contentHeight - self._viewHeight) {
           y = self._contentHeight - self._viewHeight;
         }
         self._scrollTo({y:y});
       }
       else if(keyboardHeight > 0){
         y = self._offsetY - keyboardHeight;
         if(y < 0) {
           y = 0;
         }
         self._scrollTo({y:y});
       }
     }
   }, 300);
  }

  _clearDelayScrollTimer() {
    this._scrollTimer && clearTimeout(this._scrollTimer);
  }

  _keyboardDidShow(e){
    this._isKeyboardShow = true;
    if(e.startCoordinates){
      this.setState({
        keyboardHeight:e.startCoordinates.height,
      })
    }
    else if(e.endCoordinates){
      this.setState({
        keyboardHeight:e.endCoordinates.height,
      })
    }
    this._delayScrollView();
  }

  _keyboardWillShow(e){
    this._isKeyboardShow = true;
    if(e.startCoordinates){
      this.setState({
        keyboardHeight:e.startCoordinates.height,
      })
    }
    else if(e.endCoordinates){
      this.setState({
        keyboardHeight:e.endCoordinates.height,
      })
    }
    this._delayScrollView();
  }

  _keyboardDidHide(e){
    this._isKeyboardShow = false;
    this._delayScrollView(this.state.keyboardHeight);
    this.setState({
      keyboardHeight:0,
    })
  }

  _keyboardWillHide(e){
    this._isKeyboardShow = false;
    this._delayScrollView(this.state.keyboardHeight);
    this.setState({
      keyboardHeight:0,
    })
  }

  _keyboardDidChange(e) {
    // ToastUtils.show("键盘高度改变:" + e.endCoordinates.height);
    if(this._isKeyboardShow === false) {
      return;
    }
    if(e.endCoordinates){
      this.setState({
        keyboardHeight:e.endCoordinates.height,
      })
    }
  }
}
